import { login, logout, getMenuInfo, getUserInfo } from '@/api/user'
import Layout from '@/layout'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
// vuex的状态机,根据功能模块划分为设备管理，设备点检，设备维修，设备保养等
const state = {
        token: getToken(),
        name: '',
        realName: "",
        avatar: '',
        userId: '',
        introduction: '',
        roles: [],
        basicEquipment: {},
        menuList: []
    }
    // 动态组件路径
const getViews = (view) => {
    return (resolve) => require([`@/views${view}`], resolve)
}

// 扁平数组转树

function listToTree(list) {
    var listData = [...list]
    var map = {}
    var node;
    var tree = []
    var i
    for (i = 0; i < listData.length; i++) {
        map[listData[i].id] = listData[i]
        listData[i].children = []
        if (listData[i]['meta']) {
            listData[i]['meta'] = JSON.parse(listData[i]['meta'])
        }
    }
    for (i = 0; i < listData.length; i++) {
        node = listData[i]
        if (node.level == '3' && node.parentId) {
            node['component'] = getViews(node['description'])
            node['name'] = node['menuName']
            map[node.parentId].children.push(node)
        } else if (node.level == 2) {
            node['component'] = Layout
            tree.push(node)
        } else {

        }
    }
    return tree
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
        state.introduction = introduction
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    },
    SET_BASICEQUIPMENT: (state, args) => {
        state.basicEquipment = args
    },
    SET_MENULIST: (state, args) => {
        state.menuList = args
    },
    SET_USERID: (state, args) => {
        state.userId = args
    },
    SET_REALNAME: (state, args) => {
        state.realName = args
    }
}

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { username, password } = userInfo

        return new Promise((resolve, reject) => {
            login({ username: username.trim(), password: password }).then(response => {
                const data = response
                commit('SET_TOKEN', data.access_token)

                commit('SET_USERID', data.userId)
                    // commit('SET_ROLES', ["admin"]) //roles
                    // commit('SET_NAME', data.userName)
                    // commit('SET_AVATAR', "avatar")
                    // commit('SET_INTRODUCTION', "introduction")
                setToken(data.access_token)
                resolve(data.access_token)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // get user info
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getMenuInfo(state.token).then(response => {
                // 先拿取菜单，后拉取用户角色
                const { data } = response

                const menuList = [...listToTree(data)]

                commit('SET_MENULIST', menuList)
                    // const accessRoutes = await dispatch('permission/setRouteFromData', listToTree(data), { root: true })
                    // router.addRoutes(accessRoutes)

                if (!data) {
                    reject('登陆失效,请重新登录')
                }

                // const { roles, name, avatar, introduction } = data

                // roles must be a non-empty array
                // if (!roles || roles.length <= 0) {
                //     reject('getInfo: roles must be a non-null array!')
                // }
                // console.log(listToTree(data), "--")
                getUserInfo().then(res => {
                    const { roles, userName, avatar, introduction, userId, realName } = res.data
                    data.roles = ['admin']
                    commit('SET_ROLES', ['admin']) // roles
                    commit('SET_NAME', userName)
                    commit('SET_USERID', userId)
                    commit('SET_REALNAME', realName)
                    commit('SET_AVATAR', 'avatar')
                    commit('SET_INTRODUCTION', 'introduction')
                    resolve(data)
                })

                // resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            logout(state.token).then(() => {
                commit('SET_TOKEN', '')
                commit('SET_ROLES', [])
                removeToken()
                resetRouter()
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            resolve()
        })
    },

    // Dynamically modify permissions
    changeRoles({ commit, dispatch }, role) {
        return new Promise(async resolve => {
            const token = role + '-token'

            commit('SET_TOKEN', token)
            setToken(token)

            const { roles } = await dispatch('getInfo')

            resetRouter()

            // generate accessible routes map based on roles
            const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

            // dynamically add accessible routes
            router.addRoutes(accessRoutes)

            resolve()
        })
    },
    // 设备台账
    setBasicEquipment({ commit, state }, args) {
        console.log('++++++', args)
        commit('SET_BASICEQUIPMENT', args)
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}